
let mqttclient;

import storeGlobe from "../store"
//保存mqtt推送信息
let mqttdata = {
		logList: [],//日报消息
		projectList: [],//项目消息
		approvalList: [],//审批消息
		businessList: [],//业务消息
	};

function initMqtt() {
	
	// var topic = "hello";
	// var content = "setr=can see you";
	var broker_url = "tcp://49.232.170.206:27001";
	let webSocket_URL = 'wx://49.232.170.206:61623/';
	var username = "szhzykc";
	var password = "hzy@5566.com";
	var clientId = "wspaasMqClientIdD5176F28858D07D90184F00C8E6909CC";
	
	var mqtt = require('js-mqtt/mqtt.js')
	// #ifdef H5
	console.log("APP-H5 enter");	
	var client = mqtt.connect(broker_url,{
	    username: username,
	    password: password,
	    clientId: clientId
	})
	// #endif
	// #ifdef MP-WEIXIN||APP-PLUS
	console.log("APP-PLUS enter");	
	let options = { 
		// 超时时间 
		connectTimeout: 4000, 
		// 认证信息 
		clientId: clientId, 
		username: username, 
		password: password, 
		// 心跳时间 
		keepalive: 60, 
		clean: true};
	var client = mqtt.connect(webSocket_URL,options);
	// #endif
	
	
	
	mqttclient = client;
	client.on('connect', function() {
		// client.subscribe(topic, function(err) {
		// 	if (!err) {
		// 		client.publish(topic, "1111144444")
		// 	}else{
		// 		console.log("===connnect  err===")
		// 	}
		// })
		console.log("===connnect  ok===")
	}).on('reconnect', function() {
	}).on('error', function() {
	}).on('end', function() {
	})

	//推送结果
	client.on('message', function(topic, message) {
		console.log("====get message==="+message)
		if(message)
		{
			// uni.removeStorageSync('logList')
			message = message.toString().replace(/[\r\n+]/g, '')
			mqttdata.logList=[].concat(JSON.parse(message) )
			console.log("====get message==="+message)
			let logList = []
			if(uni.getStorageSync('logList')){
				logList=uni.getStorageSync('logList')
				logList=logList.concat(JSON.parse(message))
			}else{
				logList=logList.concat(JSON.parse(message))				
			}
			
			console.log("logNewsList="+JSON.stringify(logList))
			//保存变量全局
			mqttdata.logList=logList;
			//保存vuex全局数量
			storeGlobe.state.logLength = mqttdata.logList.length
			console.log(storeGlobe.state.logLength)
			//保存cookie全局
			uni.setStorageSync('logList',logList)
		}
	})
}

function subscribe(topic){
	if(mqttclient)
	{
		console.log('subscribe topic ='+topic)
		mqttclient.subscribe(topic);
	}
	else{
		console.log('subscribe mqttclient is null')
	}
}

function publish(topic,pubmessage){
	if(mqttclient)
	{
		console.log('publish topic ='+topic+";pubmessage="+pubmessage)
		mqttclient.publish(topic,pubmessage);
	}
	else{
		console.log('publish mqttclient is null')
	}
}


module.exports = {
	mqttdata:mqttdata,
	initMqtt:initMqtt,
	mqttsubscribe:subscribe,
	mqttpublish:publish
}
